package com.xmmj.common.interceptor

import android.text.TextUtils
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 请求拦截器
 */
class RequestInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val builder = chain.request().newBuilder()
        //头部添加"登录令牌"公共参数
        builder.addHeader("token", "")
        val request = chain.request()
        if (request.body() is FormBody) { //表单请求
            //定义新的请求体
            val newFormBody = FormBody.Builder()
            //获取旧的请求体
            val oldFormBody = request.body() as FormBody?
            for (i in 0 until oldFormBody!!.size()) {
                val key = oldFormBody.encodedName(i)
                val value = oldFormBody.encodedValue(i)
                if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                    newFormBody.addEncoded(key, value)
                }
            }
            //请求体添加"时间戳"公共参数
            newFormBody.addEncoded("timestamp", System.currentTimeMillis().toString() + "")
            //把新的请求体添加到请求当中
            builder.method(request.method(), newFormBody.build())
        } else { //url请求
            val httpUrl = request.url()
                .newBuilder() //请求路径添加"时间戳"公共参数
                .addQueryParameter("timestamp", System.currentTimeMillis().toString() + "")
                .build()
            builder.url(httpUrl)
        }
        return chain.proceed(builder.build())
    }
}